package com.zhang.flink.example;

import com.zhang.flink.bean.OrderEvent;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

/**
 * @title:
 * @author: zhang
 * @date: 2022/2/13 17:01
 */
public class OrderTimeOutWithCEP {
    public static void main(String[] args) throws Exception {
        // todo 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        KeyedStream<OrderEvent, String> orderEventDS = env
                .readTextFile("/Users/apple/IdeaProjects/flink_1.13/src/main/resources/OrderLog.csv")
                .map(new MapFunction<String, OrderEvent>() {
                    @Override
                    public OrderEvent map(String value) throws Exception {
                        String[] fields = value.split(",");
                        return new OrderEvent(
                                fields[0], fields[1], fields[2],
                                Long.parseLong(fields[3]) * 1000L
                        );
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<OrderEvent>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<OrderEvent>() {
                                    @Override
                                    public long extractTimestamp(OrderEvent element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })

                )
                .keyBy(r -> r.orderId);

        //todo CEP 编程三部曲
        // 1 定义模式序
        Pattern<OrderEvent, OrderEvent> pattern = Pattern.<OrderEvent>begin("create")
                .where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent value) throws Exception {
                        return "create".equals(value.type);
                    }
                })
                .followedBy("pay")
                .where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent value) throws Exception {
                        return "pay".equals(value.type);
                    }
                })
                .within(Time.minutes(15));
        // 2 模式序列作用到流
        PatternStream<OrderEvent> patternStream = CEP.pattern(orderEventDS, pattern);
        // 3 提取事件
        SingleOutputStreamOperator<String> result = patternStream
                .select(new OutputTag<String>("no pay") {
                }, new PatternTimeoutFunction<OrderEvent, String>() {
                    @Override
                    public String timeout(Map<String, List<OrderEvent>> pattern, long timeoutTimestamp) throws Exception {
                        OrderEvent create = pattern.get("create").get(0);
                        return "订单：" + create.orderId + "只有创建没有支付";
                    }
                }, new PatternSelectFunction<OrderEvent, String>() {
                    @Override
                    public String select(Map<String, List<OrderEvent>> pattern) throws Exception {
                        OrderEvent create = pattern.get("create").get(0);
                        OrderEvent pay = pattern.get("pay").get(0);
                        return create.orderId + "在" + new Timestamp(create.ts) + "" +
                                "创建订单，并在" + new Timestamp(pay.ts) + "支付";
                    }
                });


        result.print();

        result.getSideOutput(new OutputTag<String>("no pay") {
        }).print("Timeout:");

        //todo 执行任务
        env.execute();
    }
}
